/*
 * @Description: EXCEL表创建面板
 * @Author: Rfan
 * @Date: 2022-09-22 16:32:24
 * @LastEditTime: 2023-02-07 20:10:01
 */

import { useEffect, useState } from 'react';
import {
  Button,
  Divider,
  Form,
  Input,
  message,
  Select,
  Space,
  Table,
  Tabs,
  Typography
} from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { v4 as uuidv4 } from 'uuid';
import { indexToTitle, jsonClone } from '@/utils';
import { delItemById, editItemById, getListItemValue } from '@/utils/list';
import { useTemplateManageContext } from '../../../contexts/TemplateManageContext';
import { TEMP_TYPE_CLASSIFY_EXPORT } from '../../../constants';
import type { IMetadata } from '@/interfaces/metadata';
import type { ILevel } from '@/interfaces/archiveType';

const { TabPane } = Tabs;
const { Column } = Table;
const { Option } = Select;

class ExcelItem {
  key: string;

  column: string = '';

  fieldName: string = null;

  fieldOperator: string = '';

  title: string = null;

  titleOperator: string = '';

  constructor() {
    this.key = uuidv4();
  }
}

const ExcelPane = (props: any) => {
  const { levelList, levelMetadata, form, tplData, setIndexTab, updateTemplate, closeDialog } =
    props;
  const { selectAT, methodType, tplType, typeStatusList, addTemplateTypeList, editTemplateList } =
    useTemplateManageContext();

  // 当前选中的tab
  const [currentTab, setCurrentTab] = useState<string>('');
  // excel表头下拉框相关
  const [items, setItems] = useState([]);
  // 表格内容
  const [initTable, setInitTable] = useState([]);
  // 新增的表头字段
  const [name, setName] = useState('');
  // excel列与元数据字段关系
  const [colRelation, setColRelation] = useState<any[]>([]);

  useEffect(() => {
    if (tplData?.id) {
      tplData.levelList.forEach((level: any) => {
        // levelList 增加key
        level.relationList.map(
          (item: any) =>
            (item = {
              ...item,
              key: item.column + item.title
            })
        );
      });

      form.setFieldsValue(tplData);
      setColRelation(tplData.levelList);
    } else {
      form.setFieldsValue({
        tplName: '',
        archiveTypeId: selectAT.id
      });
    }
  }, [tplData]);

  useEffect(() => {
    if (levelList?.length > 0) {
      const highestLevel = levelList.find((level: ILevel) => level.levelNum === 1);
      setCurrentTab(`${highestLevel?.level}`);
    }
  }, [levelList]);

  useEffect(() => {
    if (currentTab && JSON.stringify(levelMetadata) !== '{}') {
      setItems(levelMetadata[currentTab] || []);
      // TODO: 后期重新整理数据
      const currentData = colRelation.find((item: any) => item.level === parseInt(currentTab, 10));
      setInitTable(
        currentData?.relationList.map((_item: any) => ({
          ..._item,
          key: _item.column + _item.title
        })) || []
      );
    }
  }, [currentTab, levelMetadata]);

  /**
   * @description: tab切换
   * @param {string} key 选中的tab的key
   */
  const tabsChange = (key: string) => {
    saveTableForm();
    setCurrentTab(key);
  };

  /**
   * @description: 保存excel与元数据映射关系
   */
  const saveTableForm = () => {
    const newState = jsonClone(colRelation);
    if (newState.length > 0) {
      let flag: boolean = false;
      newState.forEach((item: any) => {
        if (item.level === parseInt(currentTab, 10)) {
          item.relationList = initTable;
          flag = true;
        }
      });
      if (!flag) {
        newState.push({
          level: parseInt(currentTab, 10),
          relationList: initTable
        });
      }
    } else {
      newState.push({
        level: parseInt(currentTab, 10),
        relationList: initTable
      });
    }
    setColRelation(newState);
    updateTemplate((state: any) => ({
      ...state,
      levelList: newState
    }));
    return newState;
  };

  /**
   * @description: 添加选项输入框变化事件
   * @param {any} evt 输入事件
   */
  const onNameChange = (evt: any) => {
    setName(evt.target.value);
  };

  /**
   * @description: 新增一个选项
   * @param {any} evt 按钮点击事件
   */
  const addItem = (evt: any) => {
    evt.preventDefault();
    if (name) {
      setItems([...items, { field_desc: name }]);
      setName('');
    }
  };

  /**
   * @description: 保存单元格操作选择的内容
   * @param {any} row
   */
  const handleSave = (row: any) => {
    const newData = jsonClone(initTable);
    const index = newData.findIndex((item: any) => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, { ...item, ...row });
    setInitTable(newData);
  };

  /**
   * @description: 清空数据
   * @param {string} key 条目key，用于定位数据
   * @param {any} record 原始条目数据
   */
  const clearItem = (key: string, record: any) => {
    const initData: any = {
      fieldName: null,
      fieldOperator: '',
      title: null,
      titleOperator: ''
    };
    setInitTable(editItemById(key, { ...record, ...initData }, initTable, 'key'));
  };

  /**
   * @description: 清空全部数据
   */
  const clearAll = () => {
    const initData: any = {
      fieldName: null,
      fieldOperator: '',
      title: null,
      titleOperator: ''
    };
    setInitTable((state) => state.map((item) => ({ ...item, ...initData })));
  };

  const deleteItem = (key: string) => {
    setInitTable(delItemById(key, initTable, 'key'));
  };

  const getFTypeByFName = (level: number, name: string) =>
    levelMetadata[level].find((item: IMetadata) => item.field_name === name)?.field_type;

  const onFinish = (values: any) => {
    const _colRelation = saveTableForm();
    if (!values.archiveTypeId) {
      values.archiveTypeId = selectAT.id;
    }
    const levelList = _colRelation.map((item: any): any => {
      return {
        ...item,
        relationList: item.relationList.map((col: any, idx: number): any => {
          return {
            column: `${indexToTitle(idx + 1)}1`,
            fieldName: col.fieldName,
            fieldOperator: col.fieldOperator,
            fieldType: getFTypeByFName(item.level, col.fieldName),
            sortNo: idx + 1,
            title: col.title,
            titleOperator: col.titleOperator
          };
        })
      };
    });
    const params = { ...tplData, ...values, tplType };
    params.levelList = levelList;
    console.log('save table', params);
    if (!tplData?.id) {
      addTemplateTypeList(params).then(() => {
        message.success('添加成功');
        setIndexTab((state: string) => `${parseInt(state, 10) + 1}`);
        // message.success('修改成功');
        closeDialog && closeDialog();
      });
    } else {
      editTemplateList(params).then(() => {
        setIndexTab((state: string) => `${parseInt(state, 10) + 1}`);
        // message.success('修改成功');
        closeDialog && closeDialog();
      });
    }
  };

  const operations = (
    <Space>
      <Button
        onClick={() => {
          setInitTable((state) => [...state, new ExcelItem()]);
        }}
      >
        增加表头
      </Button>
      <Button
        onClick={() => {
          clearAll();
        }}
      >
        清空
      </Button>
    </Space>
  );

  return (
    <>
      <Form form={form} onFinish={onFinish}>
        <Form.Item name="tplName" label="模板名称" rules={[{ required: true }]}>
          <Input />
        </Form.Item>
        <Form.Item name="archiveTypeId" label="选择档案库">
          <Select disabled style={{ width: '100%' }}>
            <Option value={selectAT.id}>{selectAT.atName}</Option>
          </Select>
        </Form.Item>
      </Form>
      <Tabs activeKey={currentTab} tabBarExtraContent={operations} onChange={tabsChange}>
        {levelList.map((level: ILevel) => (
          <TabPane tab={level.levelName} key={level.level}>
            <Table dataSource={initTable} size="small" pagination={false} bordered>
              {methodType === 1 ? (
                <Column
                  title="EXCEL列"
                  key="excelCol"
                  align="center"
                  render={(_val, _record, idx) => `${indexToTitle(idx + 1)}1`}
                />
              ) : (
                <Column
                  title="序号"
                  key="idCol"
                  align="center"
                  render={(_val, _record, idx) => `${idx + 1}`}
                />
              )}
              {getListItemValue(tplType, typeStatusList, 'type', 'code') ===
              TEMP_TYPE_CLASSIFY_EXPORT ? (
                <>
                  <Column
                    title="元数据"
                    dataIndex="fieldName"
                    key="fieldName"
                    align="center"
                    render={(val, record: any) => (
                      <Select
                        value={val}
                        style={{ width: 140 }}
                        size="small"
                        placeholder="请选择字段"
                        onChange={(value) => {
                          handleSave({ ...record, fieldName: value });
                        }}
                      >
                        {levelMetadata[level.level] &&
                          levelMetadata[level.level].map((item: IMetadata) => (
                            <Option key={item.field_name} value={item.field_name}>
                              {item.field_desc}
                            </Option>
                          ))}
                      </Select>
                    )}
                  />
                  <Column
                    title="节点名称"
                    dataIndex="title"
                    key="title"
                    align="center"
                    render={(val, record: ILevel) => (
                      <Select
                        value={val}
                        style={{ width: 200 }}
                        placeholder="请选择字段"
                        size="small"
                        dropdownRender={(menu) => (
                          <>
                            <Space align="center" style={{ padding: '0 8px 4px' }}>
                              <Input placeholder="选择字段" value={name} onChange={onNameChange} />
                              <Typography.Link
                                onClick={(evt) => {
                                  addItem(evt);
                                }}
                                style={{ whiteSpace: 'nowrap' }}
                              >
                                <PlusOutlined /> 增加
                              </Typography.Link>
                            </Space>
                            <Divider style={{ margin: '8px 0' }} />
                            {menu}
                          </>
                        )}
                        onChange={(value) => {
                          handleSave({ ...record, title: value });
                        }}
                      >
                        {items.map((item: any) => (
                          <Option key={item.field_name} value={item.field_desc}>
                            {item.field_desc}
                          </Option>
                        ))}
                      </Select>
                    )}
                  />
                </>
              ) : (
                <>
                  <Column
                    title="节点名称"
                    dataIndex="title"
                    key="title"
                    align="center"
                    render={(val, record: ILevel) => (
                      <Select
                        value={val}
                        style={{ width: 200 }}
                        placeholder="请选择字段"
                        size="small"
                        dropdownRender={(menu) => (
                          <>
                            <Space align="center" style={{ padding: '0 8px 4px' }}>
                              <Input placeholder="选择字段" value={name} onChange={onNameChange} />
                              <Typography.Link
                                onClick={(evt) => {
                                  addItem(evt);
                                }}
                                style={{ whiteSpace: 'nowrap' }}
                              >
                                <PlusOutlined /> 增加
                              </Typography.Link>
                            </Space>
                            <Divider style={{ margin: '8px 0' }} />
                            {menu}
                          </>
                        )}
                        onChange={(value) => {
                          handleSave({ ...record, title: value });
                        }}
                      >
                        {items.map((item: any) => (
                          <Option key={item.field_name} value={item.field_desc}>
                            {item.field_desc}
                          </Option>
                        ))}
                      </Select>
                    )}
                  />
                  <Column
                    title="元数据"
                    dataIndex="fieldName"
                    key="fieldName"
                    align="center"
                    render={(val, record: any) => (
                      <Select
                        value={val}
                        style={{ width: 140 }}
                        size="small"
                        placeholder="请选择字段"
                        onChange={(value) => {
                          handleSave({ ...record, fieldName: value });
                        }}
                      >
                        {levelMetadata[level.level] &&
                          levelMetadata[level.level].map((item: IMetadata) => (
                            <Option key={item.field_name} value={item.field_name}>
                              {item.field_desc}
                            </Option>
                          ))}
                      </Select>
                    )}
                  />
                </>
              )}
              <Column
                title="操作"
                dataIndex="action"
                key="action"
                align="center"
                render={(_val, record: any) => (
                  <Space size="small">
                    <Button
                      type="link"
                      size="small"
                      onClick={() => {
                        clearItem(record.key, record);
                      }}
                    >
                      清空
                    </Button>
                    <Button
                      type="link"
                      size="small"
                      danger
                      onClick={() => {
                        deleteItem(record.key);
                      }}
                    >
                      删除
                    </Button>
                  </Space>
                )}
              />
            </Table>
          </TabPane>
        ))}
      </Tabs>
    </>
  );
};

export default ExcelPane;
